import users from '../../api/users'

import {
  SHOW_SUCCESS_MSG,
  SHOW_ERROR_MSG,
  SET_USERS,
  INSERT_USER,
  UPDATE_USER,
  DELETE_USER
} from '../mutation-types'

// initial state
const state = {
  users: []
}

// getters
const getters = {
  getUsers: state => state.users
}

// actions
const actions = {
  //请求用户列表
  reqGetUser({
    commit,
    state
  }) {
    commit(SET_USERS, {
      users: []
    })
    users.getUsers(
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(SET_USERS, {
            users: result.results
          })
        }
      },
      (err) => {
        console.log(err);
      }
    )
  },
  //请求插入用户
  reqInsertUser({
    commit,
    state
  }, payload) {
    // debugger;
    users.insertUser(payload,
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(SHOW_SUCCESS_MSG, {
            message: '保存用户信息成功。',
            duration: 1000,
            needGoBack: true,
          });
        } else if (result.states == 500) {
          commit(SHOW_ERROR_MSG, {
            message: '系统内部错误，请联系系统管理员。'
          });
        }
      },
      (err) => {
        console.log(err);
      }
    )
  },
  //请求更新用户
  reqUpdateUser({
    commit,
    state
  }, payload) {
    // debugger;
    users.updateUser(payload,
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(SHOW_SUCCESS_MSG, {
            message: '保存用户信息成功。',
            duration: 1000,
            needGoBack: true,
          });
        } else if (result.states == 500) {
          commit(SHOW_ERROR_MSG, {
            message: '系统内部错误，请联系系统管理员。'
          });
        }
      },
      (err) => {
        console.log(err);
      }
    )
  },
  //请求删除用户
  reqDeleteUser({
    commit,
    state
  }, payload) {
    users.deleteUser(payload,
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(DELETE_USER, payload._id);
          commit(SHOW_SUCCESS_MSG, {
            message: '删除用户账号成功。',
            duration: 1000
          });
        } else if (result.states == 500) {
          commit(SHOW_ERROR_MSG, {
            message: '系统内部错误，请联系系统管理员。'
          });
        }
      },
      (err) => {
        console.log(err);
      }
    )
  }
}

// mutations
const mutations = {
  [SET_USERS](state, {
    users
  }) {
    state.users = users
  },
  [UPDATE_USER](state, user) {
    //TODO??
  },
  [INSERT_USER](state, user) {
    //TODO??
  },
  [DELETE_USER](stete, _id) {
    state.users = state.users.filter(user => user._id !== _id);
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
